package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {


    @Autowired
    private ApartmentFacilityService apartmentFacilityService;
    @Autowired
    private ApartmentLabelService apartmentLabelService;
    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;
    @Autowired
    private GraphInfoService graphInfoService;

    //idea误报，不管
    @Autowired
    private ProvinceInfoMapper provinceInfoMapper;

    @Autowired
    private CityInfoMapper cityInfoMapper;

    @Autowired
    private DistrictInfoMapper districtInfoMapper;

    @Autowired
    private GraphInfoMapper graphInfoMapper;

    @Autowired
    private ApplicationContext context;

    @Autowired
    private FacilityInfoMapper facilityInfoMapper;

    @Autowired
    private LabelInfoMapper labelInfoMapper;

    @Autowired
    private FeeValueMapper feeValueMapper;

    public void checkBean() {
        boolean exists1 = context.containsBean("provinceInfoMapper");
        boolean exists2 = context.containsBean("cityInfoMapper");
        boolean exists3 = context.containsBean("districtInfoMapper");
        boolean exists4 = context.containsBean("graphInfoMapper");
        System.out.println(exists1 + " " + exists2 + " " + exists3 + " " + exists4);
    }

    //这里要么全都成功，要么全都不成功，所以统一用事务
    @Transactional
    @Override
    public void saveOrUpdateApartment(ApartmentSubmitVo apartmentSubmitVo) {
        //这里有两种情况：1.新增 2.修改
        //情况一新增数据：传过来的apartmentSubmitVo的id主键为null
        //情况二修改数据：传过来的apartmentSubmitVo的id主键已经赋值过了

        // 封装区域地名
        Long provinceId = apartmentSubmitVo.getProvinceId();
        Long cityId = apartmentSubmitVo.getCityId();
        Long districtId = apartmentSubmitVo.getDistrictId();
        String provinceName = provinceInfoMapper.selectById(provinceId).getName();
        String cityName = cityInfoMapper.selectById(cityId).getName();
        String districtName = districtInfoMapper.selectById(districtId).getName();
        apartmentSubmitVo.setProvinceName(provinceName);
        apartmentSubmitVo.setCityName(cityName);
        apartmentSubmitVo.setDistrictName(districtName);

        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();

        //这里传参为什么能用ApartmentSubmitVo而非ApartmentInfo？
        //this.saveOrUpdate(apartmentSubmitVo) 能跑通，
        // 是因为 MyBatis-Plus 的通用 Service
        // 只会把 PO 里存在的字段 往 SQL 里拼，
        // 而 ApartmentSubmitVo 恰好
        // 通过继承 / 复用 PO 字段 + 类名相同
        // 被 MP 当成了“一个拥有 PO 全部主键字段的普通实体”，
        // 于是它把 VO 中能与数据库列对得上的字段 当做更新列，
        // 其余字段（省名、市名、标签列表…）自动忽略，
        // 所以不会报错，也绝不会把多余字段写进 SQL。
        // this.saveOrUpdate(apartmentSubmitVo);

        //这里需要在saveOrUpdate后面获取id，
        //因为如果新增的话，后面新增代码的id是null
        Long id = apartmentSubmitVo.getId();
        if(id != null){
            //修改
            //要先删除再新增

            // 删除配套中间表
            QueryWrapper<ApartmentFacility> apartmentFacilityQueryWrapper = new QueryWrapper<>();
            apartmentFacilityQueryWrapper.eq("apartment_id", id);
            //这里不知道配套中间表的主键id，所以这里不能用removeById()，
            //上面的id是apartment_info表的主键id
            apartmentFacilityService.remove(apartmentFacilityQueryWrapper);

            // 删除标签中间表
            QueryWrapper<ApartmentLabel> apartmentLabelQueryWrapper = new QueryWrapper<>();
            apartmentLabelQueryWrapper.eq("apartment_id", id);
            apartmentLabelService.remove(apartmentLabelQueryWrapper);


            // 删除杂费中间表
            QueryWrapper<ApartmentFeeValue> apartmentFeeValueQueryWrapper = new QueryWrapper<>();
            apartmentFeeValueQueryWrapper.eq("apartment_id", id);
            apartmentFeeValueService.remove(apartmentFeeValueQueryWrapper);


            // 删除图片表
            QueryWrapper<GraphInfo> graphInfoQueryWrapper = new QueryWrapper<>();
            graphInfoQueryWrapper.eq("item_type", ItemType.APARTMENT)
                    .and(q -> q.eq("item_id", id));
            graphInfoService.remove(graphInfoQueryWrapper);


        }
        //新增
        this.saveOrUpdate(apartmentSubmitVo);
        //为了新增重新获取id，避免id为null
        Long insertId = apartmentSubmitVo.getId();
        if (!CollectionUtils.isEmpty(facilityInfoIds)){
            ArrayList<ApartmentFacility> facilityList = new ArrayList<>();
            for (Long facilityId : facilityInfoIds) {
                ApartmentFacility apartmentFacility = ApartmentFacility.builder()
                        .apartmentId(insertId)
                        .facilityId(facilityId)
                        .build();
                apartmentFacility.setApartmentId(insertId);
                apartmentFacility.setFacilityId(facilityId);
                facilityList.add(apartmentFacility);
            }
            apartmentFacilityService.saveBatch(facilityList);
        }

        if (!CollectionUtils.isEmpty(labelIds)) {
            List<ApartmentLabel> apartmentLabelList = new ArrayList<>();
            for (Long labelId : labelIds) {
                ApartmentLabel apartmentLabel = ApartmentLabel.builder()
                        .apartmentId(insertId)
                        .labelId(labelId)
                        .build();
                apartmentLabel.setApartmentId(insertId);
                apartmentLabel.setLabelId(labelId);
                apartmentLabelList.add(apartmentLabel);
            }
            apartmentLabelService.saveBatch(apartmentLabelList);
        }

        if (!CollectionUtils.isEmpty(feeValueIds)) {
            ArrayList<ApartmentFeeValue> apartmentFeeValueList = new ArrayList<>();
            for (Long feeValueId : feeValueIds) {
                ApartmentFeeValue apartmentFeeValue = ApartmentFeeValue.builder()
                        .apartmentId(insertId)
                        .feeValueId(feeValueId)
                        .build();
                apartmentFeeValue.setApartmentId(insertId);
                apartmentFeeValue.setFeeValueId(feeValueId);
                apartmentFeeValueList.add(apartmentFeeValue);
            }
            apartmentFeeValueService.saveBatch(apartmentFeeValueList);
        }

        if (!CollectionUtils.isEmpty(graphVoList)){
            ArrayList<GraphInfo> graphInfoList = new ArrayList<>();
            for (GraphVo graphVo : graphVoList) {
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setItemType(ItemType.APARTMENT);
                graphInfo.setItemId(insertId);
                graphInfo.setName(graphVo.getName());
                graphInfo.setUrl(graphVo.getUrl());
                graphInfoList.add(graphInfo);
            }
            graphInfoService.saveBatch(graphInfoList);
        }

    }

    @Override
    public IPage<ApartmentItemVo> pageItem(IPage<ApartmentItemVo> itemVoIPage, ApartmentQueryVo queryVo) {
        IPage<ApartmentItemVo> iPage = baseMapper.pageItem(itemVoIPage, queryVo);
        return iPage;
    }

    @Override
    public ApartmentDetailVo getDetailById(Long id) {
        //这里的id为公寓id


        //获取公寓基本信息，从apartment_info表里获取
        ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();
        ApartmentInfo apartmentInfo = baseMapper.selectById(id);
        BeanUtils.copyProperties(apartmentInfo, apartmentDetailVo);


        //获取公寓相关图片，这里mapper和service都可以用，都注入了
        //我在这里使用mapper
        QueryWrapper<GraphInfo> graphInfoQueryWrapper = new QueryWrapper<>();
        graphInfoQueryWrapper.eq("item_type", ItemType.APARTMENT);
        graphInfoQueryWrapper.eq("item_id", id);
        List<GraphInfo> graphInfos = graphInfoMapper.selectList(graphInfoQueryWrapper);

        List<GraphVo> graphVoList = graphInfos.stream()
                .map(graphInfo -> {
                    GraphVo graphVo = new GraphVo();
                    // 假设 GraphVo 有对应的 setter 方法
                    graphVo.setName(graphInfo.getName());
                    graphVo.setUrl(graphInfo.getUrl());
                    // 设置其他属性...
                    return graphVo;
                })
                .collect(Collectors.toList());
        apartmentDetailVo.setGraphVoList(graphVoList);

        //获取公寓配套信息

        //这里可以在FacilityInfoMapper里实现，
        //也可以在ApartmentFacilityMapper里实现，
        //但是这是获取公寓配套信息，所以在FacilityInfoMapper里实现
        List<FacilityInfo> facilityInfos = facilityInfoMapper.selectListByApartmentId(id);
        apartmentDetailVo.setFacilityInfoList(facilityInfos);



        //获取公寓标签信息
        List<LabelInfo> labelInfos = labelInfoMapper.selectListByApartmentId(id);
        apartmentDetailVo.setLabelInfoList(labelInfos);


        //获取公寓杂费信息
        List<FeeValueVo> feeValueVos = feeValueMapper.selectListByApartmentId(id);
        apartmentDetailVo.setFeeValueVoList(feeValueVos);

        return apartmentDetailVo;
    }

    @Override
    @Transactional
    public void removeApartmentInfoById(Long id) {
        //先删除公寓信息关系表再删除公寓信息
        //要么全删除，要么不删除，所以用事务

        //删除公寓图片
        QueryWrapper<GraphInfo> graphInfoQueryWrapper = new QueryWrapper<>();
        graphInfoQueryWrapper.eq("item_type", ItemType.APARTMENT)
                .and(q -> q.eq("item_id", id));
        graphInfoService.remove(graphInfoQueryWrapper);

        // 删除标签中间表
        QueryWrapper<ApartmentLabel> apartmentLabelQueryWrapper = new QueryWrapper<>();
        apartmentLabelQueryWrapper.eq("apartment_id", id);
        apartmentLabelService.remove(apartmentLabelQueryWrapper);


        // 删除杂费中间表
        QueryWrapper<ApartmentFeeValue> apartmentFeeValueQueryWrapper = new QueryWrapper<>();
        apartmentFeeValueQueryWrapper.eq("apartment_id", id);
        apartmentFeeValueService.remove(apartmentFeeValueQueryWrapper);

        // 删除配套中间表
        QueryWrapper<ApartmentFacility> apartmentFacilityQueryWrapper = new QueryWrapper<>();
        apartmentFacilityQueryWrapper.eq("apartment_id", id);
        apartmentFacilityService.remove(apartmentFacilityQueryWrapper);

        //删除公寓信息
        this.removeById( id);

    }

    @Override
    public List<ApartmentInfo> getListInfoByDistrictId(Long id) {
        List<ApartmentInfo> apartmentInfoList = baseMapper.selectListInfoByDistrictId(id);
        return apartmentInfoList;
    }
}




